package com.shxc.smarttrade.old.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.DepositInfo;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.payeasenet.up.lib.pay.PayEasePay;
import com.payeasenet.up.lib.utils.NetWork;
import com.payeasenet.up.lib.utils.ViewUtils;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/6/6.
 */

public class RechargeActivity extends PayEasePay {

    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_excharge_rate)
    TextView tvExchargeRate;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tv_conversion)
    TextView tvConversion;
    @BindView(R.id.btn_recharge)
    Button btnRecharge;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_explain)
    TextView tvExplain;

    private MyProgressDialog dialog;
    private double rate;
    private double money;
    private double rmbAmount;
    private String orderNo;
    private boolean accountStatus = false;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    rate = (double) msg.obj;
                    tvExchargeRate.setText("(当前汇率：1美元 = " + rate + "人民币)");
                    break;
                case 1:
                    DepositInfo depositInfo = (DepositInfo) msg.obj;
                    if (depositInfo.err_code.equals("0")) {
                        DepositInfo.DataBean.InfoBean infobeen = depositInfo.getData().getInfo();
                        rmbAmount = infobeen.getRmbAmount();
                        orderNo = infobeen.getOrderNo();
                        //跳转到确认支付页面
//                        Intent intent = new Intent(RechargeActivity.this, RechargeStatusActivity.class);
//                        intent.putExtra("rmbAmount", rmbAmount);
//                        intent.putExtra("rate", rate);
//                        intent.putExtra("dollar", money);
//                        intent.putExtra("orderNo", orderNo);
//                        startActivity(intent);

                        String dispachUrl = infobeen.getDispatchUrl();
                        if (TextUtils.isEmpty(dispachUrl) || dispachUrl.equals("null")) {
                            startPayMoney();
                        } else {
                            Intent intent = new Intent(RechargeActivity.this, RechargeWebViewActivity.class);
                            intent.putExtra("name", "充值");
                            intent.putExtra("url", dispachUrl);
                            startActivity(intent);
                            overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_in);
                            //                        startPayMoney();
                        }

                    } else {
                        showToast(depositInfo.err_msg);
                    }
                    break;
            }
        }
    };

    @Override
    public void doStartUnionPayPlugin(Activity activity, String s, String s1) {
        UPPayAssistEx.startPay(activity, null, null, s, s1);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        CloseAllActivity.getScreenManager().pushActivity(this);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        startDialog();
        initListener();
        initDatas(SpUtils.getInt(this, "userId"));
    }

    /**
     * 初始化view
     */
    private void initView() {
        tvCenter.setText("充值");
        tvRight.setText("充值记录");
        accountStatus = SpUtils.getBoolean(this, "accountStatus", false);
        if (accountStatus) {
            tvExplain.setText("充值资金将直接存入您的开户经纪商：TigerWit");
            btnRecharge.setText("提交至经纪商");
        } else {
            tvExplain.setText("您当前为模拟账户，请添加经纪商账户后充值。");
            btnRecharge.setText("开设真实账户");
        }

    }

    /**
     * 初始化文本框监听器
     */
    private void initListener() {
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = etMoney.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    money = 0;
                    tvConversion.setText("¥ 0.00");
                    return;
                }

                try {
                    money = Double.parseDouble(text);
                    if (money < 50) {
                        tvConversion.setText("¥ " + BaseUtils.getDigitsData(Arith.round4(Arith.mul(money, rate), 2), 2));
                        money = 0;
                    } else {
                        tvConversion.setText("¥ " + BaseUtils.getDigitsData(Arith.round4(Arith.mul(money, rate), 2), 2));
                    }
                } catch (Exception e) {
                    showToast("请输入正确金额");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    /**
     * 初始化数据
     *
     * @param userId
     */
    private void initDatas(int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.RECHARGE_ACTIVITY_TODEPOSIT, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
                dismissDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        if (!jsonObject.get("data").isJsonNull()) {
                            JsonObject data = jsonObject.get("data").getAsJsonObject();
                            double rate = 0;
                            if (!data.get("rate").isJsonNull())
                                rate = data.get("rate").getAsDouble();
                            Message msg = Message.obtain();
                            msg.what = 0;
                            msg.obj = rate;
                            handler.sendMessage(msg);
                        } else {
                            showToast("数据异常");
                        }
                    } else {
                        showToast(errMsg);
                    }
                }
                dismissDialog();
            }
        });
    }

    /**
     * 正式支付
     */
    private void startPayMoney() {
        if (NetWork.netWorkType(getApplicationContext()) != 0) {
            String mid = "12492";
            int userId = SpUtils.getInt(RechargeActivity.this, "userId", -1);
//            String v_url = "http://218.75.40.82:8071/index.html";//测试用
            String v_url = "http://mayiforex.com/index.html ";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            java.util.Date data = new java.util.Date(System.currentTimeMillis());
            String curData = formatter.format(data);
            String oid = curData + "-" + mid + "-" + orderNo;
            if (userId == -1) {
                MyApplication.showToast(this, "账号异常，请重新登录！");
                return;
            }
            String mark = userId + "";
            String md5Key = "02Fq3UYefbwJ23ZV";
            createOrder(mid, oid, "", "", "",
                    "", "", rmbAmount + "", curData, "1",
                    "", "0", v_url, "admin",
                    "00", "000000000000000", mark, md5Key);
        } else {
            ViewUtils.toast(RechargeActivity.this, "请连接网络!", true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String msg = "";
            int msgTag = 0;//1、支付成功 2、支付失败 3、用户取消支付 4、支付异常
            String str = data.getExtras().getString("pay_result");
            if (str != null) {
                if (str.equalsIgnoreCase("success")) {
                    if (data.hasExtra("result_data")) {
                        String builder = data.getExtras().getString("result_data");
                        try {
                            JSONObject resultJson = new JSONObject(builder);
                            String sign = resultJson.getString("sign");
                            String dataOrg = resultJson.getString("data");
                            boolean ret = this.verify(dataOrg, sign, "00");
                            if (ret) {
                                msg = "支付成功！";
                                msgTag = 1;
                            } else {
                                Log.e("success0", builder);
                                msg = "支付失败！";
                                msgTag = 2;
                            }
                        } catch (JSONException var11) {
                        }
                    } else {
                        msg = "支付成功！";
                        msgTag = 1;
                    }
                } else if (str.equalsIgnoreCase("fail")) {
                    msg = "支付失败！";
                    msgTag = 2;
                } else if (str.equalsIgnoreCase("cancel")) {
                    msg = "用户取消了支付";
                    msgTag = 3;
                }
            } else {
                msg = "支付异常";
                msgTag = 4;
            }
            depositUpdata(orderNo, str);
            Intent intent = new Intent(this, RechargeResultActivity.class);
            intent.putExtra("rmbAmount", rmbAmount);
            intent.putExtra("rate", rate);
            intent.putExtra("dollar", money);
            if (msgTag == 1) {
                //跳到支付成功页面
                intent.putExtra("status", 0);
            } else {
                //跳转到支付异常界面
                intent.putExtra("status", 1);
            }
            startActivity(intent);

        }
    }

    public boolean verify(String msg, String sign64, String mode) {
        return true;
    }

    @OnClick(R.id.rl_left)
    public void onRlLeftClicked() {
        finish();
    }

    @OnClick(R.id.btn_recharge)
    public void onBtnRechargeClicked() {

        if (accountStatus) {
            //先请求服务器，获取流水号和计算后的金额
            if (money == 0) {
                showToast("请按要求输入金额");
                return;
            }
            startDialog();
            comfirmdeposit(SpUtils.getInt(this, "userId"), money);
        } else {
            startActivity(new Intent(this, ChooseBrokerActivity.class));
        }

    }

    @OnClick(R.id.tv_service_phone)
    public void tvServicePhone() {
        Uri uri = Uri.parse("tel:" + "057158239809");
        Intent dialntent = new Intent(Intent.ACTION_DIAL, uri);
        startActivity(dialntent);
    }

    @OnClick(R.id.tv_right)
    public void tvRight() {
        Intent intent = new Intent(this, AccountInfomationActivity.class);
        intent.putExtra("type", 1);
        startActivity(intent);
    }

    /**
     * 确认充值接口
     *
     * @param userId
     * @param amount
     */
    private void comfirmdeposit(int userId, double amount) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        map.put("amount", amount + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.RECHARE_ACTIVITY_COMFIRMDEPOSIT, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
                dismissDialog();
            }

            @Override
            public void success(String response, int id) {
//                Log.e("recharge", response);
//                        if (1 == 1) return;
                if (response != null) {
                    Gson gson = new Gson();
                    DepositInfo depositInfo = gson.fromJson(response, DepositInfo.class);
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = depositInfo;
                    handler.sendMessage(msg);
                } else {
                    showToast("数据异常");
                }
                dismissDialog();
            }
        });
    }

    private void startDialog() {
        if (dialog == null) {
            dialog = new MyProgressDialog(this);
            dialog.setCancelable(false);
        }
        dialog.show();
    }

    private void dismissDialog() {
        if (dialog != null)
            dialog.dismiss();
    }

    private void showToast(String str) {
        MyApplication.showToast(this, str);
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.RECHARGE_RESULT_ACTIVITY_TWO)) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        CloseAllActivity.getScreenManager().popActivity(this);

    }

    /**
     * 上传入金结果
     *
     * @param orderNo
     * @param payStatus
     */
    private void depositUpdata(String orderNo, String payStatus) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("orderNo", orderNo);
        map.put("payStatus", payStatus);
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.RECHARGE_STATUS_ACTIVITY_DEPOSIT_UPDATE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsob = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsob.get("err_code").isJsonNull())
                        errCode = jsob.get("err_code").getAsString();
                    if (!jsob.get("err_msg").isJsonNull())
                        errMsg = jsob.get("err_msg").getAsString();
                    if (!errCode.equals("0"))
                        showToast(errMsg);

                }
            }
        });
    }
}
